<?php

use Phalcon\Paginator\Adapter\Model as PaginatorModel;

trait Km
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 卡密列表
     */
    public function kmlistAction()
    {
        //当前页数
        if (!isset($this->params['page']) || empty($this->params['page'])) {
            $page = 1;
        } else {
            $page = (int)$this->params['page'];
        }
        //当前条数
        if (!isset($this->params['limit']) || empty($this->params['limit'])) {
            $pageSize = 10;
        } else {
            $pageSize = (int)$this->params['limit'];
        }
        $is_recommend          = isset($this->params['is_recommend']) ? $this->params['is_recommend'] : 0;
        $params['cate_id']     = isset($this->params['cate_id']) ? $this->params['cate_id'] : 0;
        $params['sell_status'] = isset($this->params['sell_status']) ? $this->params['sell_status'] : 1;

        $params['is_hot'] = isset($this->params['is_hot']) ? $this->params['is_hot'] : 0;
        $goods            = new Kmgoodstype();
        $list             = $goods->get_list($is_recommend, $params, '*');
        $paginator        = new PaginatorModel(
            array(
                "data"  => $list,
                "limit" => $pageSize,
                "page"  => $page
            )
        );

        $list_items = $paginator->getPaginate();

        $newlist = [];

        $db   = new SourceMaterial();
        $data = $this->transition_array($list_items->items);
        foreach ($data as $val) {
            $val['plat_type'] = $val['ids'] ? 2 : 1;

            $val['plat_name'] = '';

            if ($val['plat_type'] == 2) {
                $sourceInfo       = $db->find_by_id($val['ids']);
                if(!empty($sourceInfo)){
                    $val['plat_name'] = $sourceInfo['name'];
                }
            }
            $val['source_name'] = '';
            if (!empty($val['ids'])) {
                $name = $db->findFirstById($val['ids']);
                if ($name) {
                    $val['source_name'] = $name->name . '.' . $name->id;
                } else {
                    $val['source_name'] = '';
                }
            }
            $newlist[] = $val;
        }

        $list_items->items = $newlist;

        $this->ok($list_items);
    }


    public function transition_array($obj, $page = '')
    {
        $arr_str  = json_encode($obj);
        $arr_json = json_decode($arr_str, true);
        if (!empty($page)) {
            if ($arr_json['total_pages'] < $page) {
                $arr_json['items']   = [];
                $arr_json['current'] = $page;
                return $arr_json;
            }
        }
        return $arr_json;
    }

    /**
     * 添加卡密
     */
    public function kmeditAction()
    {
        $params                    = $this->params;
        $id                        = $params['id'];
        $tmp['goods_type_name']    = $params['goods_type_name'];
        $tmp['short_type_name']    = $params['short_type_name'];
        $tmp['icon']               = $params['icon'];
        $tmp['goods_type_id']      = $params['goods_type_id'];
        $tmp['sell_status']        = $params['sell_status'];
        $tmp['is_recommend']       = $params['is_recommend'];
        $tmp['is_hot']             = $params['is_hot'] == true ? 1 : 0;
        $tmp['cate_id']            = $params['cate_id'] ? implode(',', $params['cate_id']) : '';
        $tmp['hot_tips']           = $params['hot_tips'];
        $tmp['goods_type_id_cate'] = $params['goods_type_id_cate'];
        $tmp['product_type']       = $params['product_type'];

        $tmp['ids']     = isset($params['ids']) ? $params['ids'] : '';
        $tmp['up_desc'] = $params['up_desc'];
        $db             = new Kmgoodstype();

        if (!empty($tmp['goods_type_id'])) {
            if ($id > 0) {
                $where = "id != $id and goods_type_id = {$tmp['goods_type_id']}";
            } else {
                $where = " goods_type_id = {$tmp['goods_type_id']}";
            }

            $isId = $db->findFirst($where);
            if ($isId) {
                $this->fail(-1, '第三方ID已存在!');
            }

        }

        if ($id > 0) {

            $save = $db->findFirstById($id)->update($tmp);
        } else {
            $tmp['created_at'] = date('Y-m-d H:i:s');

            $save = $db->save($tmp);

        }
        if ($save) {
            $this->ok();
        } else {
            $this->fail(-1, '操作失败!');
        }
    }

    /**
     * 删除卡密
     */
    public function kmdelAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '缺少参数ID');
        }
        $db = new Kmgoodstype();
        if ($db->findFirstById($this->params['id'])->delete()) {
            $this->ok();
        } else {
            $this->fail(-1, '操作失败!');
        }
    }

    /**
     * 卡密分类
     */
    public function categoryAction()
    {
        $category = new Kmcategory();
        $list     = $category->find()->toarray();
        $this->ok($list);
    }

    public function editCategoryAction()
    {
        if (!isset($this->params['name']) || empty($this->params['name'])) {
            $this->fail(-1, '缺少参数name');
        }
        if (!isset($this->params['is_show'])) {
            $this->fail(-1, '缺少参数is_show');
        }
        if (!isset($this->params['sort'])) {
            $this->fail(-1, '缺少参数sort');
        }
        if (!isset($this->params['is_jingxuan'])) {
            $this->fail(-1, '缺少参数sort');
        }

        $category = new Kmcategory();
        if (!isset($this->params['id'])) {
            $category->name        = $this->params['name'];
            $category->is_show     = $this->params['is_show'];
            $category->sort        = $this->params['sort'];
            $category->is_jingxuan = $this->params['is_jingxuan'];
            $category->created_at  = date('Y-m-d H:i:s');
            if (!$category->save()) {
                $this->fail(-1, '添加失败');
            }
        } else {
            $category              = $category->findFirstById($this->params['id']);
            $category->name        = $this->params['name'];
            $category->is_show     = $this->params['is_show'];
            $category->sort        = $this->params['sort'];
            $category->is_jingxuan = $this->params['is_jingxuan'];
            if (!$category->save()) {
                $this->fail(-1, '修改失败');
            }
        }
        $this->ok('操作成功!');
    }

    public function editAdRouterAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '标签id不能为空');
        }

        $this->dbMaster->begin();
        switch ($this->params['type']) {
            case -1:
                $this->params['type'] = 2;
                break;
            case 2:
                $this->params['type']     = 2;
                $this->params['app_path'] = 'H5UserId';
                break;
            case 3:
                $this->params['type']     = 2;
                $this->params['app_path'] = "H5";
                break;
        }

        $source_materialDb = new SourceMaterial();
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $source_materialDb->name          = $this->params['name'];
            $source_materialDb->path          = $this->params['path'];
            $source_materialDb->type          = $this->params['type'];
            $source_materialDb->app_path      = $this->params['app_path'];
            $source_materialDb->url           = $this->params['url'];
            $source_materialDb->app_data      = $this->params['app_data'];
            $source_materialDb->is_tb_atuh    = $this->params['is_tb_atuh'];
            $source_materialDb->is_need_login = $this->params['is_need_login'];
            $source_materialDb->title         = $this->params['title'];
            $source_materialDb->start_color   = $this->params['start_color'];
            $source_materialDb->start_color   = $this->params['start_color'];
            $source_materialDb->end_color     = $this->params['end_color'];
            $source_materialDb->relationId    = $this->params['relationId'];
            if (!$source_materialDb->save()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '路由创建失败');
            }
        } else {
            $source_material_find_one = $source_materialDb->find_by_id_obj($this->params['id']);
            if (!$source_material_find_one) {
                $this->dbMaster->rollback();
                $this->fail(-1, '没有找到该路由记录，该路由已经被管理员删除');
            }
            $source_material_find_one->name          = $this->params['name'];
            $source_material_find_one->path          = $this->params['path'];
            $source_material_find_one->type          = $this->params['type'];
            $source_material_find_one->app_path      = $this->params['app_path'];
            $source_material_find_one->url           = $this->params['url'];
            $source_material_find_one->app_data      = $this->params['app_data'];
            $source_material_find_one->is_tb_atuh    = $this->params['is_tb_atuh'];
            $source_material_find_one->is_need_login = $this->params['is_need_login'];
            $source_material_find_one->title         = $this->params['title'];
            $source_material_find_one->start_color   = $this->params['start_color'];
            $source_material_find_one->start_color   = $this->params['start_color'];
            $source_material_find_one->end_color     = $this->params['end_color'];
            $source_material_find_one->relationId    = $this->params['relationId'];
            if (!$source_material_find_one->save()) {
                $this->dbMaster->rollback();
                $this->fail(-1, '修改路由失败');
            }
        }

        $Kmgoodstype = new Kmgoodstype();
        $info        = $Kmgoodstype->findFirstById($this->params['id']);
        if (!$info) {
            $this->fail(-1, '不存在');
        }

        $info->ids = $info->ids ? $info->ids . ',' . $source_material_find_one->id : $source_material_find_one->id;
        if (!$info->save()) {
            $this->rollback();
            $this->fail(-1, '操作失败!');
        }
        $this->dbMaster->commit();
        $this->ok([]);
    }

    public function delAdRouterAction()
    {
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, '标签id不能为空');
        }
        if (!isset($this->params['ids']) || empty($this->params['ids'])) {
            $this->fail(-1, 'ids不能为空');
        }
        $f_ad_positions = new AdPositions();
        $info           = $f_ad_positions->findFirstById($this->params['id']);
        if ($info) {
            $olg = explode(',', $info->ids);
            foreach ($olg as $key => $val) {
                if ($val == $this->params['ids']) {
                    unset($olg[$key]);
                }
            }
            $info->ids = implode(',', $olg);
            if ($info->save()) {
                $this->ok('操作成功');
            }
        }
        $this->fail(-1, '操作失败!');
    }

    /**
     * 素材列表
     */
    public function source_listAction()
    {
        $db      = new SourceMaterial();
        $find    = $db->find()->toarray();
        $newlist = [];
        foreach ($find as $val) {
            $tmp['name'] = $val['name'];
            $tmp['id']   = $val['id'];
            $newlist[]   = $tmp;
        }
        $this->ok($newlist);
    }

    /**
     * 产品分类
     */
    public function produce_cateAction()
    {
        $category            = new KmProduceCate();
        $where['conditions'] = "pid = 0";
        $list                = $category->find($where)->toarray();
        $this->ok($list);
    }

    public function produce_type_listAction()
    {
        $km_produce          = new KmProduce();
        $goods_type_id       = $this->params['goods_type_id'];
        $where['conditions'] = "goods_type_id = $goods_type_id";
        $list                = $km_produce->find($where)->toarray();
        $this->ok($list);
    }

    public function produce_type_editAction()
    {
        $km_produce = new KmProduce();
        if (isset($this->params['id'])) {
            $km_produce                     = $km_produce->findFirstById($this->params['id']);
            $km_produce->name               = $this->params['name'];
            $km_produce->goods_no           = $this->params['goods_no'];
            $km_produce->price              = $this->params['price'];
            $km_produce->official_price     = $this->params['official_price'];
            $km_produce->goods_type_id      = $this->params['goods_type_id'];
            $km_produce->goods_type_name    = $this->params['goods_type_name'];
            $km_produce->sell_status        = $this->params['sell_status'];
            $km_produce->end_price          = $this->params['end_price'];
            $km_produce->is_houtai          = $this->params['is_houtai'];
            $km_produce->discount           = $this->params['discount'];
            $km_produce->product_type       = $this->params['product_type'];
            $km_produce->product_id         = $this->params['product_id'];
            $km_produce->limit_count        = $this->params['limit_count'];
            $km_produce->recharge_tip       = $this->params['recharge_tip'];
            $km_produce->buyer_tip          = $this->params['buyer_tip'];
            $km_produce->icon               = $this->params['icon'];
            $km_produce->tips               = $this->params['tips'];
            $km_produce->goods_type_id_cate = $this->params['goods_type_id_cate'];
            if ($km_produce->save()) {
                $this->ok();
            }
        } else {
            $km_produce->name               = $this->params['name'];
            $km_produce->goods_no           = isset($this->params['goods_no']) ? $this->params['goods_no'] : '';
            $km_produce->price              = isset($this->params['price']) ? $this->params['price'] : '';
            $km_produce->official_price     = isset($this->params['official_price']) ? $this->params['official_price'] : '';
            $km_produce->goods_type_id      = isset($this->params['goods_type_id']) ? $this->params['goods_type_id'] : '';
            $km_produce->goods_type_name    = isset($this->params['goods_type_name']) ? $this->params['goods_type_name'] : '';
            $km_produce->sell_status        = isset($this->params['sell_status']) ? $this->params['sell_status'] : '';
            $km_produce->end_price          = isset($this->params['end_price']) ? $this->params['end_price'] : '';
            $km_produce->is_houtai          = isset($this->params['is_houtai']) ? $this->params['is_houtai'] : '';
            $km_produce->discount           = isset($this->params['discount']) ? $this->params['discount'] : '';
            $km_produce->product_type       = isset($this->params['product_type']) ? $this->params['product_type'] : '';
            $km_produce->product_id         = isset($this->params['product_id']) ? $this->params['product_id'] : '';
            $km_produce->limit_count        = isset($this->params['limit_count']) ? $this->params['limit_count'] : '';
            $km_produce->recharge_tip       = isset($this->params['recharge_tip']) ? $this->params['recharge_tip'] : '';
            $km_produce->buyer_tip          = isset($this->params['buyer_tip']) ? $this->params['buyer_tip'] : '';
            $km_produce->icon               = isset($this->params['icon']) ? $this->params['icon'] : '';
            $km_produce->tips               = isset($this->params['tips']) ? $this->params['tips'] : '';
            $km_produce->goods_type_id_cate = isset($this->params['goods_type_id_cate']) ? $this->params['goods_type_id_cate'] : '';
            if ($km_produce->save()) {
                $this->ok();
            }
        }
        $this->fail(-1);
    }



    public function del_productAction(){
        if (!isset($this->params['id']) || empty($this->params['id'])) {
            $this->fail(-1, 'id不能为空');
        }
        $kmGoodsType = new Kmgoodstype();
        $km_goods_type_find = $kmGoodsType->findFirstById($this->params['id']);
        if($km_goods_type_find->delete()){
            $this->ok([]);
        }else{
            $this->fail(-1,'删除失败');
        }

    }
}
